package com.zliblike_platform.service.impl;

import com.zliblike_platform.dto.UserLoginDTO;
import com.zliblike_platform.dto.UserRegisterDTO;
import com.zliblike_platform.dto.UserUpdateDTO;
import com.zliblike_platform.entity.User;
import com.zliblike_platform.mapper.UserMapper;
import com.zliblike_platform.service.UserService;
import com.zliblike_platform.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    @Transactional
    public boolean register(UserRegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (isUsernameExists(registerDTO.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (isEmailExists(registerDTO.getEmail())) {
            throw new RuntimeException("邮箱已被注册");
        }
        
        // 检查两次密码是否一致
        if (!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())) {
            throw new RuntimeException("两次密码不一致");
        }
        
        // 创建用户对象
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setEmail(registerDTO.getEmail());
        user.setNickname(registerDTO.getUsername()); // 默认昵称为用户名
        
        // 密码加密
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        
        // 设置默认值
        user.setAvatar("/static/images/default-avatar.png");
        user.setLevel(1); // 普通用户
        user.setPoints(0);
        user.setDailyDownloadLimit(5); // 默认每日下载5次
        user.setAccountLevel("普通用户");
        user.setRole("ROLE_USER");
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        user.setEnabled(true);
        
        // 保存用户
        return userMapper.insert(user) > 0;
    }

    @Override
    public boolean login(UserLoginDTO loginDTO) {
        // 根据用户名或邮箱查询用户
        User user = findByUsernameOrEmail(loginDTO.getUsername());
        
        // 用户不存在
        if (user == null) {
            return false;
        }
        
        // 账号未启用
        if (!user.getEnabled()) {
            throw new RuntimeException("账号已被禁用");
        }
        
        // 验证密码
        return passwordEncoder.matches(loginDTO.getPassword(), user.getPassword());
    }

    @Override
    public UserVO getUserById(Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            return null;
        }
        
        // 转换为VO对象
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        
        // 获取用户今日已下载次数
        Integer usedDownloads = getUserDailyDownloads(id);
        userVO.setUsedDownloads(usedDownloads);
        
        return userVO;
    }

    @Override
    @Transactional
    public boolean updateUser(Long id, UserUpdateDTO updateDTO) {
        User user = userMapper.selectById(id);
        if (user == null) {
            return false;
        }
        
        // 检查用户名是否已存在（如果要更改用户名）
        if (!user.getUsername().equals(updateDTO.getUsername()) && isUsernameExists(updateDTO.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已存在（如果要更改邮箱）
        if (!user.getEmail().equals(updateDTO.getEmail()) && isEmailExists(updateDTO.getEmail())) {
            throw new RuntimeException("邮箱已被注册");
        }
        
        // 更新用户信息
        user.setUsername(updateDTO.getUsername());
        user.setEmail(updateDTO.getEmail());
        user.setUpdatedAt(LocalDateTime.now());
        
        return userMapper.update(user) > 0;
    }

    @Override
    @Transactional
    public boolean updatePassword(Long id, String oldPassword, String newPassword) {
        User user = userMapper.selectById(id);
        if (user == null) {
            return false;
        }
        
        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new RuntimeException("原密码错误");
        }
        
        // 加密新密码
        String encodedPassword = passwordEncoder.encode(newPassword);
        
        // 更新密码
        return userMapper.updatePassword(id, encodedPassword) > 0;
    }

    @Override
    @Transactional
    public boolean addPoints(Long id, Integer points) {
        if (points <= 0) {
            throw new RuntimeException("积分必须大于0");
        }
        
        return userMapper.updatePoints(id, points) > 0;
    }

    @Override
    public boolean isDownloadLimitReached(Long id) {
        // 获取用户每日下载限制
        Integer limit = userMapper.getDailyDownloadLimit(id);
        if (limit == null) {
            return true;
        }
        
        // 获取用户今日已下载次数
        Integer used = getUserDailyDownloads(id);
        if (used == null) {
            used = 0;
        }
        
        // 判断是否达到上限
        return used >= limit;
    }

    @Override
    public User findByUsernameOrEmail(String usernameOrEmail) {
        // 先按用户名查询
        User user = userMapper.selectByUsername(usernameOrEmail);
        
        // 如果用户名不存在，再按邮箱查询
        if (user == null) {
            user = userMapper.selectByEmail(usernameOrEmail);
        }
        
        return user;
    }

    @Override
    public boolean isEmailExists(String email) {
        return userMapper.existsByEmail(email);
    }

    @Override
    public boolean isUsernameExists(String username) {
        return userMapper.existsByUsername(username);
    }
    
    @Override
    public Integer getUserDailyDownloads(Long userId) {
        return userMapper.getUserDailyDownloads(userId);
    }
} 